#!/bin/bash

set -eu

source $SNAP/actions/common/utils.sh
KUBECTL="$SNAP/kubectl --kubeconfig=$SNAP/client.config"

clean_cluster() {
  echo "Calling clean_cluster"
  # Clean the cluster
  NSES=$($KUBECTL get ns -o=name | awk -F/ '{print $2}' | paste -s --delimiters=' ')
  for NS in $NSES
  do
    echo "Cleaning resources in namespace $NS"
    # Remove all resource types except the standard k8s apiservices themselves
    $KUBECTL delete --all $($KUBECTL api-resources -o name --verbs=delete --namespaced=true | grep -v '^apiservices$' | paste -s --delimiters=',') --namespace="$NS"
  done
  REMOVEABLE_NSES=$($KUBECTL get ns -o=name | awk -F/ '{if ($2 !~ /^(default|kube-public|kube-system)$/) print}' | paste -s --delimiters=' ')
  if [ -n "$REMOVEABLE_NSES" ]
  then
    $KUBECTL delete $REMOVEABLE_NSES
  fi

  echo "Removing CRDs"
  $KUBECTL delete --all customresourcedefinitions.apiextensions.k8s.io

  # Wait for 200 secs at most.
  echo "Waiting for kubernetes resources to be released"
  n=0
  until [ $n -ge 10 ]
  do
    ($KUBECTL get po --all-namespaces 2>&1 | grep "No resources found." 2>&1 > /dev/null) && break
    n=$[$n+1]
    sleep 20
  done

  echo "Cleaning up addons client binaries.."
  if [  -d "$SNAP_DATA/bin/" ] 
  then
    sudo rm -rf "$SNAP_DATA/bin/"
  fi
}

exit_if_stopped

if systemctl status snap.${SNAP_NAME}.daemon-docker >& /dev/null
then
  sudo systemctl restart snap.${SNAP_NAME}.daemon-docker
elif systemctl status snap.${SNAP_NAME}.daemon-containerd >& /dev/null
then
  sudo systemctl restart snap.${SNAP_NAME}.daemon-containerd
fi
clean_cluster
sudo systemctl restart snap.${SNAP_NAME}.daemon-apiserver
